//
//  LXStatisticsViewController.m
//  LiXingZuLin
//
//  Created by ypj on 2022/9/5.
//

#import "LXStatisticsViewController.h"
#import "LXStatisticsItemCell.h"
#import "LXTimeChooseView.h"
#import "LXStatisticsScreenView.h"
#import "LXStatisticsModel.h"
#import "LXStatisticsListViewController.h"
#import "QuanXianModel.h"

#define kItemHeight KHeightScale(88)
#define kItemCount 2


@interface LXStatisticsViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic) UICollectionView *collectionView;
@property (nonatomic) NSMutableArray *data;
@property (nonatomic) UIView *topView;
@property (nonatomic) UIButton *leftScreenBtn,*rightScreenBtn;
@property (nonatomic) LXTimeChooseView *timeView;
@property (nonatomic) LXStatisticsScreenView *screenView;

@property (nonatomic) NSArray *leftScreenAry,*rightScreenAry;
@property (nonatomic) NSString *leftScreenKey,*rightScreenKey;

/**overall全部统计 car车辆统计 customer客户统计 finance财务统计*/
@property (nonatomic) NSString *type;
/**today week month year custom*/
@property (nonatomic) NSString *dateType;
/**自定义时间开始和结束*/
@property (nonatomic) NSString *startDate, *endDate;
@property (nonatomic) BOOL isReLoad;

@end


@implementation LXStatisticsViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.isReLoad) {
        [self loadData];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.data = [NSMutableArray array];
    
    // 默认全部统计
    self.leftScreenKey = @"overall";
    // 默认今日统计
    self.rightScreenKey = @"today";
    
    
    [self layoutUI];
    
    [self getJurisdiction];
    
}

-(void)layoutUI{
    
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F7F8FA"];
    
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth / 2 - 100, KStatuesBarHeight, 200, 40)];
     [self.view addSubview:titleLab];
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.text = @"统计";
    titleLab.font = [UIFont systemFontOfSize:FontSize(18) weight:UIFontWeightMedium];
    titleLab.textColor = UIColor.blackColor;
     
    UIView *navLine = [[UIView alloc] initWithFrame:CGRectMake(0, kViewTopHeight - 1, kScreenWidth, 1)];
    navLine.backgroundColor = [UIColor colorWithHexString:@"#F2F2F2"];
    [self.view addSubview:navLine];
    
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, kViewTopHeight, ScreenWidth, 94)];
    topView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:topView];
    [topView setClipsToBounds:YES];
    self.topView = topView;
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kViewTopHeight);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(50);
    }];
    
    UIButton *leftScreenBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, 15, 100, 20)];
    [topView addSubview:leftScreenBtn];
    leftScreenBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    leftScreenBtn.titleLabel.font = Fond14;
    [leftScreenBtn setTitle:@"全部统计" forState:UIControlStateNormal];
    [leftScreenBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    [leftScreenBtn setTitleColor:ColorWith3C6CFC forState:UIControlStateSelected];
    [leftScreenBtn setImage:[UIImage imageNamed:@"acc_down"] forState:UIControlStateNormal];
    [leftScreenBtn setImage:[UIImage imageNamed:@"acc_downSelect"] forState:UIControlStateSelected];
    [leftScreenBtn addTarget:self action:@selector(clickleftScreenBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.leftScreenBtn = leftScreenBtn;
    [leftScreenBtn setIconInRightWithSpacing:3];

    UIButton *rightScreenBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 115, 15, 100, 20)];
    [topView addSubview:rightScreenBtn];
    rightScreenBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    rightScreenBtn.titleLabel.font = Fond14;
    [rightScreenBtn setTitle:@"今日统计" forState:UIControlStateNormal];
    [rightScreenBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    [rightScreenBtn setTitleColor:ColorWith3C6CFC forState:UIControlStateSelected];
    [rightScreenBtn setImage:[UIImage imageNamed:@"acc_down"] forState:UIControlStateNormal];
    [rightScreenBtn setImage:[UIImage imageNamed:@"acc_downSelect"] forState:UIControlStateSelected];
    rightScreenBtn.hidden = YES;
    self.rightScreenBtn = rightScreenBtn;
    [rightScreenBtn addTarget:self action:@selector(clickrightScreenBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [rightScreenBtn setIconInRightWithSpacing:3];

    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 50, kScreenWidth, 1)];
    line.backgroundColor = [UIColor colorWithHexString:@"#F2F2F2"];
    [topView addSubview:line];
    
    LXTimeChooseView *timeView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([LXTimeChooseView class]) owner:self options:nil][0];
    [timeView setClipsToBounds:YES];
    timeView.frame = CGRectMake(0, line.Y_height, ScreenWidth, 43);
    [topView addSubview:timeView];
    self.timeView = timeView;
    [timeView setClickCellBlock:^(NSString * _Nonnull value,int type) {
        
    
        if (type == 1 && !StringIsEmpty(self.endDate)) {
            if([NSString compareDate:value withDate:self.endDate withFormat:k_DateFormat] == -1){
                showAlert(@"开始日期不能小于结束日期");
                return;
            }
        }
        else if (type == 2 && !StringIsEmpty(self.startDate)) {
            if([NSString compareDate:value withDate:self.startDate withFormat:k_DateFormat] == 1){
                showAlert(@"结束日期不能大于开始日期");
                return;
            }
        }
        [self loadData];
    }];
    

    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake((kScreenWidth - 30)/kItemCount,kItemHeight);
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 10, 10);
    flowLayout.minimumLineSpacing= 10;
    flowLayout.minimumInteritemSpacing = 10;
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    [self.view addSubview:collectionView];
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(topView.mas_bottom).offset(10);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.backgroundColor = [UIColor colorWithHexString:@"#F7F8FA"];
    [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([LXStatisticsItemCell  class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([LXStatisticsItemCell class])];
    self.collectionView = collectionView;

    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadData];
    }];
 

}


-(void)loadData{
    
    
    NSString *url = [NSString stringWithFormat:@"%@%@",DOMAIN_URL,GET_GetCompanyStatisticsList];
    
    
    //统计:  overall全部统计 car车辆统计 customer客户统计 finance财务统计
    NSString *type;
    for (LXStatisticsModel *model in self.leftScreenAry) {
        if(model.isSel){
            type = model.key;
            break;
        }
    }
    self.type = type;
    
    
    //日期:   today当天  week本周  month本月  year本年  custom自定义
    NSString *dateType;
    if ([type isEqualToString:@"overall"]||
        [type isEqualToString:@"finance"]) {
        for (LXStatisticsModel *model in self.rightScreenAry) {
            if(model.isSel){
                dateType = model.key;
                break;
            }
        }
    }
    // 指定日期
    NSString *startDate, *endDate;
    if ([dateType isEqualToString:@"custom"]) {
        startDate = self.timeView.leftTimeBtn.titleLabel.text;
        endDate = self.timeView.rightTimeBtn.titleLabel.text;
    }
    
    
    self.dateType = dateType;
    self.startDate = startDate;
    self.endDate = endDate;
    NSDictionary *dic = @{
        @"type":type,
        @"dateType":dateType,
        @"startDate":startDate,
        @"endDate":endDate,
    };
    
    [MSNetworkManager getRevertUrl:url params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        
        [self.collectionView.mj_header endRefreshing];
        
        
        if (isSuccess) {
            self.data = [LXStatisticsModel mj_objectArrayWithKeyValuesArray:resonseObj];
            [self.collectionView reloadData];
        }
      
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
        
    } withShowHud:NO];
    
    
}

#pragma mark -- 请求权限
-(void)getJurisdiction{
        
    // 权限工作台
    NSString *url = [NSString stringWithFormat:@"%@",POST_Jurisdiction];
    [MSNetworkManager postRevertUrl:url params:@{} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        NSMutableArray *tempAry = [QuanXianModel mj_objectArrayWithKeyValuesArray:resonseObj];
        NSMutableArray *leftScreenAry = [NSMutableArray array];
        int i = 0;
        for (QuanXianModel *model in tempAry){
            if ([model.permission containsString:@"statistics"]) {
                NSArray *keyAry = [model.permission componentsSeparatedByString:@"_"];
                NSDictionary *dic = @{
                    @"name":model.name,
                    @"isSel":i==0?@(YES):@(NO),
                    @"key":keyAry.lastObject
                };
                [leftScreenAry addObject:dic];
                i++;
            }
           

        }
        self.leftScreenAry = [LXStatisticsModel mj_objectArrayWithKeyValuesArray:leftScreenAry];
        
        
        LXStatisticsModel *model = self.leftScreenAry.firstObject;
        self.leftScreenKey = model.key;
        [self.leftScreenBtn setTitle:model.name forState:UIControlStateNormal];
        //overall全部统计 car车辆统计 customer客户统计 finance财务统计
        if ([model.key isEqualToString:@"overall"] ||
            [model.key isEqualToString:@"finance"]) {
            self.rightScreenBtn.hidden = NO;
        }
        else {
            self.rightScreenBtn.hidden = YES;
        }
        self.isReLoad = YES;
        [self loadData];
        
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
    } withShowHud:NO];
     

    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.data.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    LXStatisticsItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([LXStatisticsItemCell class]) forIndexPath:indexPath];
    LXStatisticsModel *model = self.data[indexPath.row];
    cell.titleLb.text = model.name;
    cell.subTitleLb.text = model.value;
    return cell;
   
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    LXStatisticsModel *model = self.data[indexPath.row];
    
    // 已租车辆 待租车辆
    if (model.type == YZCL || model.type == DZCL) {
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        appDelegate.carType = model.type;
        UIViewController *controller = appDelegate.window.rootViewController;
        LiXingMainTabbarVC *rvc = (LiXingMainTabbarVC *)controller;
        [rvc setSelectedIndex:3];
        return;
    }
    // 全部客户  已租车客户 租金逾期客户
    else if (model.type == QBKH || model.type == YZCKH || model.type == ZJYQKH) {
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        appDelegate.customerType = model.type;
        UIViewController *controller = appDelegate.window.rootViewController;
        LiXingMainTabbarVC *rvc = (LiXingMainTabbarVC *)controller;
        [rvc setSelectedIndex:4];
        
        if (model.type == QBKH) {
            [kNotifyCenter postNotificationName:@"customerStatusChange" object:@"0"];
        }
        else if (model.type == YZCKH){
            [kNotifyCenter postNotificationName:@"customerStatusChange" object:@"2"];
        }
        else if (model.type == ZJYQKH){
            [kNotifyCenter postNotificationName:@"customerStatusChange" object:@"3"];
        }
        
        return;
    }
    
    
    LXStatisticsListViewController *vc = [[LXStatisticsListViewController alloc] init];
    NSString *titleName = model.name;
    if ([model.name containsString:@"("] || [model.name containsString:@")"]) {
        NSArray *ary = [model.name componentsSeparatedByString:@"("];
        titleName = ary.firstObject;
    }
    vc.titleName = titleName;
    vc.statisticsType = model.type;
    vc.dateType = self.dateType;
    vc.startDate = self.startDate;
    vc.endDate = self.endDate;
    if ([self.type isEqualToString:@"customer"] && (model.type == TYJKH ||model.type == JZKH)) {
        vc.startDate = [NSString getNowDateWithFormat:@"yyyy-MM-dd"];
        vc.endDate = [NSString getNowDateWithFormat:@"yyyy-MM-dd"];
    }
    [self pushToNextController:vc];
}

// MARK: 点击左侧筛选
-(void)clickleftScreenBtnAction:(UIButton *)sender{
    
    
    if(sender.isSelected)return;
    
    self.rightScreenBtn.selected = NO;
    
    sender.selected = YES;
    
    self.screenView.data =  self.leftScreenAry;
    WEAKSELF
    [self.screenView setClickCellBlock:^(LXStatisticsModel * _Nonnull model) {
        
        sender.selected = NO;

        [weakSelf.screenView removeFromSuperview];
        weakSelf.screenView  = nil;
        
        if (ObjectIsEmpty(model))return;

        [sender setTitle:model.name forState:UIControlStateNormal];
        
        
        weakSelf.leftScreenKey = model.key;
        
        // 全部统计 财务统计
        if ([model.key isEqualToString:@"overall"] ||
            [model.key isEqualToString:@"finance"]) {
            weakSelf.rightScreenBtn.hidden = NO;
            
            if ([weakSelf.rightScreenKey isEqualToString:@"custom"]) {
                [weakSelf.topView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(94);
                }];
            }
           
        }
        else{
            weakSelf.rightScreenBtn.hidden = YES;
            [weakSelf.topView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(50);
            }];
        }
        
        [weakSelf loadData];
        
    }];
}
//MARK: 点击右侧筛选
-(void)clickrightScreenBtnAction:(UIButton *)sender{
    
    if(sender.isSelected)sender.selected = NO;

    
    self.leftScreenBtn.selected = NO;
    
    sender.selected = YES;
    
    self.screenView.data =  self.rightScreenAry;
    WEAKSELF
    [self.screenView setClickCellBlock:^(LXStatisticsModel *model) {
        
        sender.selected = NO;
        
        [weakSelf.screenView removeFromSuperview];
        weakSelf.screenView  = nil;
        
        if (ObjectIsEmpty(model))return;
        
        [sender setTitle:model.name forState:UIControlStateNormal];
        
        weakSelf.rightScreenKey = model.key;
        
        if ([model.key isEqualToString:@"custom"]) {
            [weakSelf.topView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(94);
            }];
        }
        else{
            [weakSelf.topView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(50);
            }];
        }
        
        
        
        [weakSelf loadData];
        
    }];
    
}


- (LXStatisticsScreenView *)screenView{
    if (!_screenView) {
        _screenView = [[LXStatisticsScreenView alloc] initWithFrame:CGRectMake(0, kViewTopHeight + 50, ScreenWidth, ScreenHeight)];
        [self.tabBarController.view addSubview:_screenView];
    }
    return _screenView;
}

- (NSArray *)rightScreenAry{
    if (!_rightScreenAry) {
        NSArray *ary = @[
            @{
                @"name":@"今日统计",
                @"key":@"today",
                @"isSel":@(YES),
            },
            @{
                @"name":@"本周统计",
                @"key":@"week",
                @"isSel":@(NO),
            },
            @{
                @"name":@"本月统计",
                @"key":@"month",
                @"isSel":@(NO),
            },
            @{
                @"name":@"指定时间",
                @"key":@"custom",
                @"isSel":@(NO),
            },
        ];
        _rightScreenAry = [LXStatisticsModel mj_objectArrayWithKeyValuesArray:ary];
    }
    return _rightScreenAry;
}


@end
